/**
 * Copyright 2010 Butin Kirill <kiryaka@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.flexupload.stream
{
	import flash.utils.clearTimeout;
	import flash.utils.setTimeout;
	
	import mx.controls.Alert;
	import mx.rpc.events.ResultEvent;
	
	import org.flexupload.model.FilePart;
	import org.flexupload.model.ServerReply;
	import org.flexupload.remote.FlexuploadService;
	import org.flexupload.status.FileThreadStatus;

	public class ThreadStream
	{		
		private var remoteService:FlexuploadService;
		private var filePart:FilePart;
		private var fileStream:FileStream;
		private var requestTimeOutId:uint;
		private var fileThreadStatus:FileThreadStatus;
		public function ThreadStream(fileStream:FileStream, remoteService:FlexuploadService){
			this.remoteService = remoteService;
			this.fileStream = fileStream;
			this.fileThreadStatus = new FileThreadStatus(this.fileStream.getFileStatus());
			remoteService.addEventListener(ResultEvent.RESULT, uploadResultHandler);
			uploadPart();
		}
		private function finishWork():void{
			remoteService.removeEventListener(ResultEvent.RESULT, uploadResultHandler);
			fileStream.finishThread();
			remoteService.markServiceAsFree();
		}
		private function uploadPart():void{
			if(!filePart) filePart = fileStream.getFilePart();
			
			if(!filePart){
				return finishWork();
			}

			remoteService.uploadFilePart(fileStream.getFileInfo(), filePart);
			requestTimeOutId = setTimeout(uploadTimeOut, 15000);
		}
		private function uploadTimeOut():void{
			//Alert.show("Timeout in file: " + fileStream.getFileInfo().name);
			uploadPart();
			//trace("Upload time out on file: " + fileStream.getFileInfo().toString());
		}
		private function uploadResultHandler(event:ResultEvent):void{
			var serverReply:ServerReply = ServerReply(event.result);
			if (serverReply.type != ServerReply.TYPE_SAVE_PART ||
				serverReply.fileInfo.name != fileStream.getFileInfo().name ||
				serverReply.status != ServerReply.SUCCESS
			){
				trace("Get bad upload part");
				return;
			}
			
			//trace("--- File part: " + serverReply.fileInfo.toString());

			clearTimeout(requestTimeOutId);
			requestTimeOutId = 0;
			
			fileThreadStatus.updateBytesTransfered(serverReply.bytesTransfered);
			
			filePart = null;
			
			uploadPart();
		}
	}
}